//
//  CollectionViewReloadDataViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/22.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import RxDataSources

class CollectionViewReloadDataViewController: UIViewController {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    let refreshButton = UIBarButtonItem(title: "刷新", style: .plain, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "取消", style: .plain, target: nil, action: nil)
    
    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "36.UICollectionView的使用3：刷新集合数据"
        view.backgroundColor = .white
        
        test()
    }
    
    func test() {
        
        self.navigationItem.rightBarButtonItems = [refreshButton,cancelButton]
        
        //定义布局方式以及单元格大小
        let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: 100, height: 70)
        //创建一个重用的单元格
        collectionView.register(UINib(nibName: "TitleCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
        //随机的表格数据
        let randomResult = refreshButton.rx.tap.asObservable()
            .throttle(1, scheduler: MainScheduler.instance) //在主线程中操作，1秒内值若多次改变，取最后一次
            .startWith(()) //加这个为了让一开始就能自动请求一次数据
            .flatMapLatest{
                self.getRandomResult().takeUntil(self.cancelButton.rx.tap)
            }
            .share(replay: 1)
         
        //创建数据源
        let dataSource = RxCollectionViewSectionedReloadDataSource
            <SectionModel<String, Int>>(
            configureCell: { (dataSource, collectionView, indexPath, element) in
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",
                                                for: indexPath) as! TitleCollectionViewCell
                cell.titleL.text = "\(element)"
                return cell}
        )
         
        //绑定单元格数据
        randomResult
            .bind(to: collectionView.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
    }
    
    //获取随机数据
    func getRandomResult() -> Observable<[SectionModel<String, Int>]> {
        print("正在请求数据......")
        let items = (0 ..< 5).map {_ in
            Int(arc4random_uniform(100000))
        }
        let observable = Observable.just([SectionModel(model: "S", items: items)])
        return observable.delay(2, scheduler: MainScheduler.instance)
    }

}
